﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

using Xc.DataAccess.Core;
using Xc.DataAccess.Core.Services;
using Xc.DataAccess.OneNetCore.Models;

namespace Xc.DataAccess.OneNetCore.Services
{
    /// <summary>
    /// OneNet服务
    /// </summary>
    public class OneNetService : IOneNetService
    {
        private readonly IConverterService converterService;
        private readonly IHttpClientFactory httpClientFactory;

        public OneNetService(IConverterService converterService, IHttpClientFactory httpClientFactory)
        {
            this.converterService = converterService;
            this.httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 创建设备
        /// </summary>
        /// <param name="createDeviceRequest"></param>
        /// <returns></returns>
        public async Task<ResultData<DeleteDeviceRespondCore?>> CreateDevice(CreateDeviceRequest createDeviceRequest)
        {
            var res = await RequestAsync<CreateDeviceRequest, CreateDeviceRespond>(createDeviceRequest);
            if(res != null && res.IsSuccess)
            {
                return res?.Data;
            } else
            {
                return ResultData<DeleteDeviceRespondCore?>.Reject(res.Message, default);
            }
        }

        /// <summary>
        /// 更新设备信息
        /// </summary>
        /// <param name="updateDevcieRequest"></param>
        /// <returns></returns>
        public async Task<Result> UpdateDevice(UpdateDevcieRequest updateDevcieRequest)
        {
            var res = await RequestAsync<UpdateDevcieRequest, UpdateDevcieResponse>(updateDevcieRequest);
            if(res != null && res.IsSuccess)
            {
                return res?.Data;
            } else
            {
                return Result.Reject(res.Message);
            }
        }

        /// <summary>
        /// 配置信息
        /// </summary>
        public OneNetSetting Options { get; set; }

        internal async Task<ResultData<TRespond>> RequestAsync<TRequest, TRespond>(TRequest request)
            where TRequest : RequestCore<TRespond>
        {
            var requestbody = converterService.ToJsonString(request);
            using var http = httpClientFactory.CreateClient(Options.HttpClientFactoryName);
            var path = request.RequestPath + request.QueryParameter();
            Uri uri = new Uri(new Uri(Options.BaseAddress), path);
            StringContent content = null;
            if(request.SendBody == true)
            {
                content = new StringContent(requestbody, Encoding.UTF8, request.ContentType);
            }
            var req = new HttpRequestMessage { Content = content, Method = request.HttpMethod, RequestUri = uri, };
            req.Headers.Add("api-key", Options.ApiKey);
            var respond = await http.SendAsync(req);
            if(!respond.IsSuccessStatusCode)
            {
                return ResultData<TRespond>.Reject(respond.ReasonPhrase, default);
            }
            var text = await respond.Content.ReadAsStringAsync();
            return ResultData<TRespond>.Accept("通信成功", converterService.FromJsonString<TRespond>(text));
        }

        /// <summary>
        /// 删除指定设备
        /// </summary>
        /// <param name="deviceid">设备编号</param>
        /// <returns></returns>
        public async Task<Result> DeleteDevice(string deviceid)
        {
            var res = await RequestAsync<DeleteDeviceRequest, DeleteDeviceRespond>(
                new DeleteDeviceRequest { DeviceId = deviceid });
            if(res != null && res.IsSuccess)
            {
                return res?.Data;
            } else
            {
                return Result.Reject(res.Message);
            }
        }

        /// <summary>
        /// 查询设备信息
        /// </summary>
        /// <param name="queryDevicesRequest"></param>
        /// <returns></returns>
        public async Task<ResultData<QueryDevicesRespondCore>> GetDevices(QueryDevicesRequest queryDevicesRequest)
        {
            var res = await RequestAsync<QueryDevicesRequest, QueryDevicesRespond>(queryDevicesRequest);
            if(res != null && res.IsSuccess)
            {
                return res?.Data;
            } else
            {
                return ResultData<QueryDevicesRespondCore>.Reject(res.Message, default);
            }
        }

        /// <summary>
        /// 查询设备状态
        /// </summary>
        /// <param name="queryDevicesStatusRequest"></param>
        /// <returns></returns>
        public async Task<ResultData<QueryDevicesStatusRespondCore>> GetDeviceStatus(
            QueryDevicesStatusRequest queryDevicesStatusRequest)
        {
            var res = await RequestAsync<QueryDevicesStatusRequest, QueryDevicesStatusRespond>(
                queryDevicesStatusRequest);
            if(res != null && res.IsSuccess)
            {
                return res?.Data;
            } else
            {
                return ResultData<QueryDevicesStatusRespondCore>.Reject(res.Message, default);
            }
        }
    }
}
